#!/bin/bash

APP_NAME=base-frame
APP_VERSION=1.0-SNAPSHOT

# 等待应用启动的时间 单位：s
APP_START_TIMEOUT=30

# jar包的名字
DIST_JAR=lib/${APP_NAME}-dist-$APP_VERSION.jar
API_JAR=lib/${APP_NAME}-api-$APP_VERSION.jar
DUBBO_JAR=lib/${APP_NAME}-dubbo-facade-$APP_VERSION.jar,lib/${APP_NAME}-dubbo-impl-$APP_VERSION.jar
JOB_JAR=lib/${APP_NAME}-job-$APP_VERSION.jar
MQ_JAR=lib/${APP_NAME}-mq-$APP_VERSION.jar

# jvm params
JAVA_OPTS=${JAVA_OPTS:-"-Xms1g -Xmx1g -Xmn512m"}
SERVER_OPTS=${SERVER_OPTS:-"-server -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=128m -Xss512k -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:LargePageSizeInBytes=128m -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:+PrintGCDetails -Xloggc:$APP_LOGS_PATH/gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=dump.hprof -XshowSettings:vm"}

usage="Usage: deploy.sh (start|stop|restart) <api[,dubbo,job,mq]> "
# if no args specified, show usage
if [ $# -le 1 ]; then
    usage
fi

command=$1
shift
apps=$1
shift

BIN_DIR=$(cd $(dirname ${BASH_SOURCE[0]}); pwd)
APP_HOME=`cd "$BIN_DIR/.."; pwd`
APP_LOG_DIR=$APP_HOME/logs
APP_PID_DIR=$APP_HOME/pid

# 创建出相关目录
mkdir -p ${APP_LOG_DIR}
mkdir -p ${APP_PID_DIR}

pid=$APP_PID_DIR/$APP_NAME.pid
log=$APP_LOG_DIR/$APP_NAME.out

cd $APP_HOME

if [ "$command" == "start" -o "$command" == "restart" ]; then
  LOADER_PATH="-Dloader.path=conf"
  for var in ${apps//,/ }
  do
     case $var in
          api)
              LOADER_PATH=$LOADER_PATH,$API_JAR
              ;;
          dubbo)
              LOADER_PATH=$LOADER_PATH,$DUBBO_JAR
              ;;
          job)
              LOADER_PATH=$LOADER_PATH,$JOB_JAR
              ;;
          mq)
              LOADER_PATH=$LOADER_PATH,$MQ_JAR
              ;;
          *)
              echo "Error: No app named '$APP' was found."
              exit 1
      esac
  done
fi

health_check() {
    HEALTH_CHECK_URL="http://localhost:8080/ping"
    exptime=0
    echo "checking ${HEALTH_CHECK_URL}"
    while true
        do
            status_code=`curl -L -o /dev/null --connect-timeout 5 -s -w %{http_code}  ${HEALTH_CHECK_URL}`
            if [ "$?" != "0" ]; then
               echo -n -e "\rapplication not started. return $?. code is $status_code"
            else
                echo "code is $status_code"
                if [ "$status_code" == "200" ];then
                    break
                fi
            fi
            sleep 2
            ((exptime++))

            echo -e "\rWait app to pass health check: $exptime..."

            if [ $exptime -gt ${APP_START_TIMEOUT} ]; then
                echo 'app start failed'
                exit 1
            fi
        done
    echo "check ${HEALTH_CHECK_URL} success"
}

start_application() {
    echo "starting java process, loging to $log"
    exec_command="$JAVA_OPTS $SERVER_OPTS $LOADER_PATH -jar $DIST_JAR"
    echo "nohup java $exec_command > $log 2>&1 &"
    nohup java $exec_command > $log 2>&1 &
    echo $! > $pid
    echo "started java process"
}

stop_application() {
   checkjavapid=`ps -ef | grep java | grep ${APP_NAME} | grep -v grep |grep -v 'deploy.sh'| awk '{print$2}'`

   if [[ ! $checkjavapid ]];then
      echo -e "\rno java process"
      return
   fi

   echo "stop java process"
   times=60
   for e in $(seq 60)
   do
        sleep 1
        COSTTIME=$(($times - $e ))
        checkjavapid=`ps -ef | grep java | grep ${APP_NAME} | grep -v grep |grep -v 'deploy.sh'| awk '{print$2}'`
        if [[ $checkjavapid ]];then
            kill -9 $checkjavapid
            echo -e  "\r  -- stopping java lasts `expr $COSTTIME` seconds."
        else
            echo -e "\rjava process has exited"
            break;
        fi
   done
   echo ""
}

start() {
    start_application
    tail -50f $log
    health_check
}

stop() {
    stop_application
}

usage() {
    echo $usage
    exit 2
}

case "$command" in
    start)
        start
    ;;
    stop)
        stop
    ;;
    restart)
        stop
        start
    ;;
    *)
        usage
    ;;
esac